﻿using Aspose.Words;
using DocumentFormat.OpenXml.Wordprocessing;
using JetBrains.Annotations;
using NP.BPMReportPlatform.BPMPlatform;
using NP.BPMReportPlatform.DBHelper;
using NP.BPMReportPlatform.Entities.BPM_Business;
using NP.BPMReportPlatform.Entities.BPM_Business.SceneSalesTechDoc;
using NP.BPMReportPlatform.IU;
using NP.BPMReportPlatform.SceneSalesTechDoc.Dtos;
using NP.BPMReportPlatform.SeminarManage.Dtos;
using NP.BPMReportPlatform.Utils;
using SqlSugar;
using SqlSugar.DistributedSystem.Snowflake;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Application.Dtos;

namespace NP.BPMReportPlatform.SceneSalesTechDoc
{
    public class TUCSceneSalesTechDocService : BPMReportPlatformAppService, ITUCSceneSalesTechDocService
    {
        private readonly SqlSugarClient _db, _dbEngine;
        private readonly IBPMPlatformAppService _iBPMPlatformApp;
        private readonly IBPMUtilsAppService _bPMUtilsApp;

        public TUCSceneSalesTechDocService(ISqlSugarAppService sqlSugarAppService
            , IBPMPlatformAppService iBPMPlatformApp
            , IBPMUtilsAppService bPMUtilsApp)
        {
            _db = sqlSugarAppService.GetBusinessInstance();
            _iBPMPlatformApp = iBPMPlatformApp;
            _bPMUtilsApp = bPMUtilsApp;
        }
        /// <summary>
        /// 获取
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PagedResultDto<TUCSceneSalesTechDocOutput>> GetAllAsync(TUCSceneSalesTechDocInput input)
        {
            RefAsync<int> totalCount = 0;
            var listQueryable = GetQueryableList(input);
            var listViewDto = await listQueryable.ToPageListAsync(input.PageIndex, input.PageSize, totalCount);
            var userId = await _iBPMPlatformApp.GetUserAsync(CurrentUser.UserName);
            listViewDto.ForEach(x =>
            {
                x.Url = _bPMUtilsApp.GetProcessUrl(x.InstanceNumber, userId);
            });
            return new PagedResultDto<TUCSceneSalesTechDocOutput>()
            {
                TotalCount = totalCount,
                Items = listViewDto,
            };
        }

        /// <summary>
        /// 导出
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<List<TUCSceneSalesTechDocOutput>> Export1Async(TUCSceneSalesTechDocInput input)
        {
            var listQueryable = GetQueryable(input);
            var listViewDto = listQueryable.ToList();
            return listViewDto;
        }

        /// <summary>
        /// 设置作废状态
        /// </summary>
        /// <param name="orderNum"></param>
        /// <returns></returns>
        public async Task<bool> SetStatus(string orderNum)
        {
            try
            {
                var result = await _db.Queryable<TUSceneSalesTechDocHeader>().Where(x => x.InstanceNumber.Equals(orderNum)).FirstAsync();
                if (result == null)
                {
                    return false;
                }
                result.StateText = "已作废";
                await _db.Updateable(result).ExecuteCommandAsync();
                return true;
            }
            catch (Exception)
            {
                return false;
            }

        }

        /// <summary>
        /// 获取查询条件
        /// </summary>
        /// <returns></returns>
        public async Task<List<AreaOutput>> GetArea()
        {
            var list = await _db.Queryable<TUSceneSalesTechDocConfig>().Where(x => x.Type.Equals("dept") || x.Type.Equals("productLine"))
                .Select(x => new AreaOutput()
                {
                    Name = x.SourceValue,
                    Type = x.Type
                }).Distinct().ToListAsync();

            var actions = await _db.Queryable<TUSceneSalesTechDocConfig>().Where(x => x.Type.Equals("action"))
                .Select(x => new AreaOutput()
                {
                    Name = x.SourceValue1,
                    Type = x.Type
                }).Distinct().ToListAsync();
            List<AreaOutput> newList = list.Union(actions).ToList();
            return newList;
        }

        /// <summary>
        /// 查询列表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        private ISugarQueryable<TUCSceneSalesTechDocOutput> GetQueryableList(TUCSceneSalesTechDocInput input)
        {
            var listQueryable = _db.Queryable<TUCSceneSalesTechDocHeader, TUCSceneSalesTechDocProductLineDetails>(
                (x, p) => new JoinQueryInfos(JoinType.Left, x.InstanceNumber == p.InstanceNumber))
                    .WhereIF(!string.IsNullOrEmpty(input.InstanceNumber), (x, p) => x.InstanceNumber == input.InstanceNumber)
                    .WhereIF(!string.IsNullOrEmpty(input.AddName), (x, p) => x.AddUserName == input.AddName)
                    .WhereIF(!string.IsNullOrEmpty(input.StateText), (x, p) => x.StateText == input.StateText)
                    .WhereIF(!string.IsNullOrEmpty(input.Factory), (x, p) => x.Factory == input.Factory)
                    .WhereIF(!string.IsNullOrEmpty(input.BusinessNum), (x, p) => x.BusinessNum == input.BusinessNum)
                    .WhereIF(!string.IsNullOrEmpty(input.ProjectName), (x, p) => x.ProjectName == input.ProjectName)
                    .WhereIF(!string.IsNullOrEmpty(input.Action), (x, p) => x.Action == input.Action)
                    .WhereIF(!string.IsNullOrEmpty(input.ProductLine), (x, p) => p.ProductLine == input.ProductLine)
                    .WhereIF(!string.IsNullOrEmpty(input.ServiceApproveName), (x, p) => x.ServiceApproveName.Contains(input.ServiceApproveName))
                    .WhereIF(input.StartCreationTime != null && input.EndCreationTime != null, x => x.AddTime >= input.StartCreationTime
                    && x.AddTime.AddDays(-1) <= input.EndCreationTime)
                    .Where((x, p) => x.Source != "CRM二期" && x.StateText != "待发起")
                    .Select((x, p) => new TUCSceneSalesTechDocOutput()
                    {
                        InstanceNumber = x.InstanceNumber,
                        Factory = x.Factory,//项目落地大区
                        ProjectLocation = x.ProjectLocation,//项目所在地
                        SalesPerson = x.SalesPerson,//落地销售员
                        ProjectName = x.ProjectName,//项目名称
                        StateText = x.StateText,//状态
                        SaleAction = x.SaleAction,//服务动作，销售填写
                        ServiceApproveName = x.ServiceApproveName,//服务人员
                        AddUserName = x.AddUserName,//创建人
                    }).Distinct().OrderBy(x => x.AddTime, OrderByType.Desc);
            return listQueryable;
        }

        /// <summary>
        /// 导出查询
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        private ISugarQueryable<TUCSceneSalesTechDocOutput> GetQueryable(TUCSceneSalesTechDocInput input)
        {
            var listQueryable = _db.Queryable<TUCSceneSalesTechDocHeader, TUCSceneSalesTechDocProductLineDetails, TUCSceneSalesTechDocParamDetails>(
                (x, p, d) => new JoinQueryInfos(JoinType.Left, x.InstanceNumber == p.InstanceNumber,
                JoinType.Left, x.InstanceNumber == d.InstanceNumber))
                .WhereIF(!string.IsNullOrEmpty(input.InstanceNumber), (x, p) => x.InstanceNumber == input.InstanceNumber)
                    .WhereIF(!string.IsNullOrEmpty(input.AddName), (x, p) => x.AddUserName == input.AddName)
                    .WhereIF(!string.IsNullOrEmpty(input.StateText), (x, p) => x.StateText == input.StateText)
                    .WhereIF(!string.IsNullOrEmpty(input.Factory), (x, p) => x.Factory == input.Factory)
                    .WhereIF(!string.IsNullOrEmpty(input.BusinessNum), (x, p) => x.BusinessNum == input.BusinessNum)
                    .WhereIF(!string.IsNullOrEmpty(input.ProjectName), (x, p) => x.ProjectName == input.ProjectName)
                    .WhereIF(!string.IsNullOrEmpty(input.Action), (x, p) => x.Action == input.Action)
                    .WhereIF(!string.IsNullOrEmpty(input.ProductLine), (x, p) => p.ProductLine == input.ProductLine)
                    .WhereIF(!string.IsNullOrEmpty(input.ServiceApproveName), (x, p) => x.ServiceApproveName.Contains(input.ServiceApproveName))
                .WhereIF(input.StartCreationTime != null && input.EndCreationTime != null, x => x.AddTime >= input.StartCreationTime
                && x.AddTime.AddDays(-1) <= input.EndCreationTime)
                .Where((x, p, d) => x.Source != "CRM二期" && x.StateText != "待发起")
                .Select((x, p, d) => new TUCSceneSalesTechDocOutput()
                {
                    InstanceNumber = x.InstanceNumber,
                    AddUserName = x.AddUserName,
                    AddTime = x.AddTime,
                    StateText = x.StateText,//状态
                    SalesPerson = x.SalesPerson,//落地销售员
                    Division = x.Division,//事业部
                    CostCenter = x.CostCenter,//项目落地成本中心
                    Factory = x.Factory,//项目落地大区
                    SalesDept = x.SalesDept,//项目落地销售部
                    RequirementSpecification = x.RequirementSpecification,//需求说明
                    RequirementType = x.RequirementType,//需求类型
                    CityLevel = x.CityLevel,//城市等级
                    BusinessNum = x.BusinessNum,
                    ProjectName = x.ProjectName,
                    ProjectLocation = x.ProjectLocation,
                    XMYJJE = x.XMYJJE,
                    CoatingArea = x.CoatingArea,
                    CustomerCode = x.CustomerCode,
                    CustomerName = x.CustomerName,
                    PhaseName = x.PhaseName,
                    Linkman = x.Linkman,
                    Telephone = x.Telephone,
                    Address = x.Address,
                    Notes = x.Notes,
                    RepeatReason = x.RepeatReason,
                    ProcessNode = x.ProcessNode,
                    ServiceObject = x.ServiceObject,
                    Action = x.Action,
                    ArrivedTime = x.ArrivedTime != null ? x.ArrivedTime.Value.ToString("yyyy-MM-dd") : "",
                    RequirementDescription = x.RequirementDescription,
                    ProductLine = p.ProductLine,
                    System = p.System,
                    DetailSystem = p.DetailSystem,
                    ConstructionEffect = p.ConstructionEffect,
                    ColorNum = p.ColorNum,
                    SingleBlockArea = p.SingleBlockArea,
                    GrassrootsSituation = p.GrassrootsSituation,
                    TemplateProperties = p.TemplateProperties,
                    ConsumptionClaim = p.ConsumptionClaim,
                    SamplePaintNo = p.SamplePaintNo,
                    PSystem = d.System,
                    ActualConsumption = d.ActualConsumption,
                    SampleConsumption = d.SampleConsumption,
                    RecommendedConsumption = d.RecommendedConsumption,
                    TemplateReplicability = d.TemplateReplicability,
                    OtherConstructionParameters = d.OtherConstructionParameters,
                    IsLaborServices = x.IsLaborServices,
                    LaborServicesName = x.LaborServicesName,
                    EsimatedCycle = x.EsimatedCycle,
                    ConfirmDate = x.ConfirmDate,
                    ServiceApproveName = x.ServiceApproveName,
                    DealerOpinion = x.DealerOpinion,
                    RejectReason = x.RejectReason,
                    FailReason = x.FailReason,
                    RealTime = x.RealTime != null ? x.RealTime.Value.ToString("yyyy-MM-dd") : "",
                    RealCycle = x.RealCycle,
                    SaleAction = x.SaleAction,
                    WarnDescribe = x.WarnDescribe,
                    Opinion = x.Opinion,
                    TotalScore = x.TotalScore,
                    Satisfaction = x.Satisfaction,
                    SatisfactionSuggest = x.SaleAction,
                    ImprovementMeasures = x.ImprovementMeasures,
                    Key1 = x.ScoreKey1,
                    Value1 = x.ScoreValue1,
                    Key2 = x.ScoreKey2,
                    Value2 = x.ScoreValue2,
                    Key3 = x.ScoreKey3,
                    Value3 = x.ScoreValue3,
                    Key4 = x.ScoreKey4,
                    Value4 = x.ScoreValue4,
                    Key5 = x.ScoreKey5,
                    Value5 = x.ScoreValue5,
                    JoinJF = x.JoinJF,
                    JFName = x.JFName,
                    JoinZBF = x.JoinZBF,
                    ZBFName = x.ZBFName,
                    JoinJLF = x.JoinJLF,
                    JLFName = x.JLFName,
                    JoinSGDW = x.JoinSGDW,
                    SGDWName = x.SGDWName,
                    JoinQT = x.JoinQT,
                    QTName = x.QTName,
                }).OrderBy(x => x.AddTime, OrderByType.Desc);
            return listQueryable;
        }
    }
}
